import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @Description: 螺旋矩阵 II
 * 给你一个正整数 n ，生成一个包含 1 到 n平方 所有元素，
 * 且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 * @Date:Create in 17:03  2022/6/8
 */
public class generateMatrix0059 {
    public static void main(String[] args) {
        int[][] arr = generateMatrix1(4);
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                System.out.println(arr[i][j]);
            }
        }

    }

    public static int[][] generateMatrix1(int n) {
        //最终数组
        int[][] arr = new int[n][n];
        int size = n * n;
        //模拟的方向数组
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int directionIndex = 0;
        int row = 0, col = 0;

        //标记数组位置是否使用过
        int[][] use = new int[n][n];
//        System.out.println(Arrays.toString(use));

        for (int i = 1; i < size + 1; i++) {
            arr[row][col] = i;
            use[row][col] = 1;
            int nextRow = row + directions[directionIndex][0];
            int nextCol = col + directions[directionIndex][1];
            if (nextCol < 0 || nextCol >= n || nextRow >= n || use[nextRow][nextCol]==1){
                directionIndex = (directionIndex+1)%4;
            }

            row += directions[directionIndex][0];
            col += directions[directionIndex][1];
            System.out.println(row+" "+col);

        }
        return arr;

    }
}
